package br.com.mundodaprata.store.data.gen;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import br.com.mundodaprata.store.data.Repository;
import br.com.mundodaprata.store.data.RepositoryFactoryJDBC;
import br.com.mundodaprata.store.model.Address;
import br.com.mundodaprata.store.model.Client;
import br.com.mundodaprata.store.model.Street;
import br.com.mundodaprata.store.model.User;
import br.com.mundodaprata.store.model.UserType;

public class ClientGen implements DataGen{

   @Override
   public void gen() throws Exception {
      Set<String> users = new HashSet<String>();
      List<Client> clients = new ArrayList<Client>();
      
      File file = new File("C:\\java\\clients.txt");
      FileReader fr = new FileReader(file);
      BufferedReader reader = new BufferedReader(fr);
      String line;
      
      DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
      
      while ((line = reader.readLine()) != null) {
         String[] data = line.split(";");
         
         Client client = new Client();
         client.setName(data[0]);
         client.setDocumentType(data[1]);
         client.setDocument(data[2]);
         
         Street street = new Street();
         street.setCode(Long.parseLong(data[3]));
         
         Address address = new Address(street);
         address.setNumber(Integer.parseInt(data[4]));
         
         client.setAddress(address);
         client.setBirthday(formatter.parse(data[5]));
         client.setEmail(data[6]);
         
         User user = new User();
         String email = client.getEmail();
         user.setUsername(email.substring(0, email.indexOf("@")));
         user.setPassword("102030");
         user.setType(UserType.CLIENT);
         
         if(!users.add(user.getUsername())){
            int count = 0;
            
            String username = user.getUsername() + count++;
            
            while(!users.add(username)){
               username = user.getUsername() + count++;
            }
            
            user.setUsername(username);
         }
         
         client.setUser(user);
         
         clients.add(client);
      }
      
      Repository<Client> jdbc = RepositoryFactoryJDBC.create(Client.class);
      jdbc.insert(clients.toArray(new Client[clients.size()]));
      jdbc.closeConnection();
   }
   
}